package com.zf.shuashua.manager;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.aliyun.svideo.common.utils.AppInfoUtils;
import com.blankj.utilcode.util.AppUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.DownProgress;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.mg.MGRewardActivity;
import com.zf.shuashua.advert.mg.ReportLocationType;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.utils.MD5Util;

import java.io.File;

public class AdDownloadManager {

    private volatile static AdDownloadManager singleton = null;

    private AdDownloadManager() {
    }

    public static AdDownloadManager getInstance() {
        if (singleton == null) {
            synchronized (AdDownloadManager.class) {
                if (singleton == null) {
                    singleton = new AdDownloadManager();
                }
            }
        }
        return singleton;
    }


    /**
     * @param url
     */
    public void installApk(Context context, String url) {
        Toast.makeText(context, "开始下载", Toast.LENGTH_LONG).show();
        FileDownloader.setup(context);
        final String savePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator;
        FileDownloader.getImpl().create(url).setPath(savePath, true).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
//                MLog.logd("下载完成：" + task.getTargetFilePath());
                AppUtils.installApp(task.getTargetFilePath());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();
//        final String rootPath = getDiskCachePath(context);
//        HttpData.getInstance().downloadApk(url, new ACallback<DownProgress>() {
//            boolean isStart = false;
//
//            @Override
//            public void onSuccess(DownProgress data) {
//                if (!isStart) {
//                    isStart = true;
//                    Toast.makeText(context, "开始下载", Toast.LENGTH_SHORT).show();
//                }
//                if (data.isDownComplete()) {
//                    // 安装apk
//                    String apkPath = rootPath + File.separator + "download" + File.separator + MD5Util.encryptMD5ToString(url) + ".apk";
//
//                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    Uri dateUri;
//                    File apkFile = new File(apkPath);
//                    if (!apkFile.exists()) {
//                        Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                    // 判断版本大于等于7.0
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
//                        dateUri = FileProvider.getUriForFile(context, context.getPackageName() + ".ZFfileProvider", apkFile);
//                        // 给目标应用一个临时授权
//                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    } else {
//                        dateUri = Uri.fromFile(apkFile);
//                    }
//                    intent.setDataAndType(dateUri, "application/vnd.android.package-archive");
//                    context.startActivity(intent);
//                }
//            }
//
//            @Override
//            public void onFail(int errCode, String errMsg) {
//                Toast.makeText(context, "下载失败：" + errMsg, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    private String getDiskCachePath(Context context) {
        String cachePath;
        if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable())
                && context.getExternalCacheDir() != null) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }


    /**
     * 判断SD卡是否可用
     *
     * @return true : 可用<br>false : 不可用
     */
    private boolean isSDCardEnable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * SD卡是否可用.
     */
    private boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sd = new File(Environment.getExternalStorageDirectory().getPath());
            return sd.canWrite();
        } else {
            return false;
        }
    }
}
